package it.storm.solution;

/**
 * 面试题 01.07. 旋转矩阵（与 48 同）
 * https://leetcode-cn.com/problems/rotate-matrix-lcci/
 */
public class Solutions_mianshi_01_07 {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3},
                        {4, 5, 6},
                        {7, 8, 9}};  // change:{{7, 4, 1},
//                                                {8, 5, 2},
//                                                {9, 6, 3}};

//        int[][] matrix = {{5, 1, 9, 11},
//                          {2, 4, 8, 10},
//                          {13, 3, 6, 7},
//                          {15, 14, 12, 16}};  // change: {{15, 13, 2, 5},
//                                                        {14, 3, 4, 1},
//                                                        {12, 6, 8, 9},
//                                                        {16, 7, 10, 11}}
        rotate(matrix);
        System.out.println(matrix);
    }
    public static void rotate(int[][] matrix) {
        if (matrix == null) {
            return;
        }
        // 规律：以左上-右下对角线为轴，进行翻转;再对每行进行翻转，完成矩阵 90 度的翻转
        int row = matrix.length;
        if (row <= 1) {
            return;
        }
        int col = matrix[0].length;
        // 以左上-右下对角线为轴，进行翻转
        for (int i = 1; i < row; i++) {
            for (int j = 0; j < i; j++) {
                // 两两交换
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
        // 对每行进行翻转
        for (int i = 0; i < row; i++) {
            int left = 0, right = col - 1;
            while (left < right) {
                // 两两交换
                int temp = matrix[i][left];
                matrix[i][left] = matrix[i][right];
                matrix[i][right] = temp;
                left ++;
                right --;
            }
        }
    }
}
